<template>
  <div class="community-enhanced">
    <!-- 顶部导航 -->
    <van-nav-bar title="维权社区" fixed>
      <template #right>
        <van-icon name="search" size="18" @click="$router.push('/search')" />
      </template>
    </van-nav-bar>

    <!-- 社区统计数据 -->
    <div class="community-stats" v-if="statsData">
      <div class="stats-grid">
        <div class="stat-item">
          <div class="stat-number">{{ statsData.totalPosts || 0 }}</div>
          <div class="stat-label">总帖子数</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ statsData.resolvedPosts || 0 }}</div>
          <div class="stat-label">已解决</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ statsData.activeUsers || 0 }}</div>
          <div class="stat-label">活跃用户</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ Math.round(statsData.successRate || 0) }}%</div>
          <div class="stat-label">成功率</div>
        </div>
      </div>
    </div>

    <!-- 高频维权场景 -->
    <div class="frequent-scenarios" v-if="frequentScenarios.length">
      <div class="section-header">
        <h3>高频维权场景</h3>
        <span class="more-btn" @click="showAllScenarios">查看更多</span>
      </div>
      <div class="scenarios-grid">
        <div
          v-for="scenario in frequentScenarios.slice(0, 6)"
          :key="scenario.id"
          class="scenario-item"
          @click="filterByScenario(scenario.categoryId)"
        >
          <div class="scenario-icon">
            <van-icon :name="getScenarioIcon(scenario.categoryId)" />
          </div>
          <div class="scenario-info">
            <div class="scenario-name">{{ scenario.name }}</div>
            <div class="scenario-count">{{ scenario.count }}个案例</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 精选成功案例 -->
    <div class="success-cases" v-if="successCases.length">
      <div class="section-header">
        <h3>精选成功案例</h3>
        <span class="more-btn" @click="showAllSuccessCases">查看更多</span>
      </div>
      <div class="cases-list">
        <div
          v-for="case_ in successCases.slice(0, 3)"
          :key="case_.id"
          class="case-item"
          @click="goToPostDetail(case_.id)"
        >
          <div class="case-badge">成功</div>
          <div class="case-content">
            <div class="case-title">{{ case_.title }}</div>
            <div class="case-summary">{{ case_.content }}</div>
            <div class="case-meta">
              <span class="case-amount" v-if="case_.amount">
                追回金额：¥{{ case_.amount }}
              </span>
              <span class="case-time">{{ formatTime(case_.createTime) }}</span>
            </div>
          </div>
          <div class="case-stats">
            <div class="stat">
              <van-icon name="good-job-o" />
              <span>{{ case_.likeCount }}</span>
            </div>
            <div class="stat">
              <van-icon name="eye-o" />
              <span>{{ case_.viewCount }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 热门讨论 -->
    <div class="hot-posts" v-if="hotPosts.length">
      <div class="section-header">
        <h3>热门讨论</h3>
        <span class="more-btn" @click="showAllHotPosts">查看更多</span>
      </div>
      <div class="hot-list">
        <div
          v-for="(post, index) in hotPosts.slice(0, 5)"
          :key="post.id"
          class="hot-item"
          @click="goToPostDetail(post.id)"
        >
          <div class="hot-rank" :class="{ 'top-three': index < 3 }">
            {{ index + 1 }}
          </div>
          <div class="hot-content">
            <div class="hot-title">{{ post.title }}</div>
            <div class="hot-meta">
              <span class="hot-comments">{{ post.commentCount }}回复</span>
              <span class="hot-time">{{ formatTime(post.createTime) }}</span>
            </div>
          </div>
          <div class="hot-indicator">
            <van-icon name="fire-o" color="#ff6b35" />
          </div>
        </div>
      </div>
    </div>

    <!-- 快速入口 -->
    <div class="quick-actions">
      <div class="action-grid">
        <div class="action-item" @click="goToPublish">
          <van-icon name="edit" />
          <span>发布求助</span>
        </div>
        <div class="action-item" @click="goToAiDiagnosis">
          <van-icon name="chat-o" />
          <span>AI诊断</span>
        </div>
        <div class="action-item" @click="goToTemplates">
          <van-icon name="description" />
          <span>文书模板</span>
        </div>
        <div class="action-item" @click="goToMyPosts">
          <van-icon name="orders-o" />
          <span>我的帖子</span>
        </div>
      </div>
    </div>

    <!-- 最新帖子 -->
    <div class="latest-posts">
      <div class="section-header">
        <h3>最新帖子</h3>
        <span class="more-btn" @click="goToAllPosts">查看全部</span>
      </div>
      
      <!-- 帖子列表 -->
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div
            v-for="post in postList"
            :key="post.id"
            class="post-item"
            @click="goToPostDetail(post.id)"
          >
            <!-- 帖子头部 -->
            <div class="post-header">
              <div class="user-info">
                <img :src="post.avatar || defaultAvatar" class="avatar" />
                <div class="user-details">
                  <div class="nickname">{{ post.nickname || '匿名用户' }}</div>
                  <div class="post-time">{{ formatTime(post.createTime) }}</div>
                </div>
              </div>
              <div class="post-status">
                <span v-if="post.isResolved" class="status-tag resolved">已解决</span>
                <span v-else class="status-tag pending">求助中</span>
              </div>
            </div>

            <!-- 帖子内容 -->
            <div class="post-content">
              <div class="post-title">{{ post.title }}</div>
              <div class="post-summary">{{ post.content }}</div>
              
              <!-- 图片 -->
              <div v-if="post.images && post.images.length" class="post-images">
                <img
                  v-for="(image, index) in post.images.slice(0, 3)"
                  :key="index"
                  :src="image"
                  class="post-image"
                  @click.stop="previewImage(post.images, index)"
                />
                <div v-if="post.images.length > 3" class="more-images">
                  +{{ post.images.length - 3 }}
                </div>
              </div>

              <!-- 标签 -->
              <div v-if="post.tags" class="post-tags">
                <span
                  v-for="tag in post.tags.split(',')"
                  :key="tag"
                  class="tag"
                >
                  {{ tag }}
                </span>
              </div>
            </div>

            <!-- 帖子底部 -->
            <div class="post-footer">
              <div class="post-stats">
                <span class="stat-item">
                  <van-icon name="eye-o" />
                  {{ post.viewCount }}
                </span>
                <span class="stat-item">
                  <van-icon name="chat-o" />
                  {{ post.commentCount }}
                </span>
              </div>
              <div class="post-actions">
                <div
                  class="action-item"
                  :class="{ active: post.isLiked }"
                  @click.stop="toggleLike(post)"
                >
                  <van-icon :name="post.isLiked ? 'good-job' : 'good-job-o'" />
                  <span>{{ post.likeCount }}</span>
                </div>
                <div
                  class="action-item"
                  :class="{ active: post.isCollected }"
                  @click.stop="toggleCollect(post)"
                >
                  <van-icon :name="post.isCollected ? 'star' : 'star-o'" />
                  <span>收藏</span>
                </div>
              </div>
            </div>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>

    <!-- 底部导航 -->
    <van-tabbar v-model="activeTab" @change="onTabChange">
      <van-tabbar-item icon="home-o" to="/home">首页</van-tabbar-item>
      <van-tabbar-item icon="chat-o" to="/community">社区</van-tabbar-item>
      <van-tabbar-item icon="orders-o" to="/templates">工具</van-tabbar-item>
      <van-tabbar-item icon="user-o" to="/profile">我的</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showImagePreview } from 'vant'
import { useUserStore } from '@/stores/user'
import { 
  getPostList, 
  getHotPosts, 
  getSuccessCases, 
  getFrequentScenarios,
  getCommunityStats,
  likePost, 
  collectPost 
} from '@/api/community'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const activeTab = ref(1)
const refreshing = ref(false)
const loading = ref(false)
const finished = ref(false)

// 数据
const statsData = ref(null)
const frequentScenarios = ref([])
const successCases = ref([])
const hotPosts = ref([])
const postList = ref([])
const defaultAvatar = 'https://img.yzcdn.cn/vant/cat.jpeg'

// 分页参数
const pageParams = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 方法
const loadCommunityData = async () => {
  try {
    // 并行加载各种数据
    const [statsRes, scenariosRes, casesRes, hotRes] = await Promise.allSettled([
      getCommunityStats(),
      getFrequentScenarios(),
      getSuccessCases({ current: 1, size: 5 }),
      getHotPosts({ current: 1, size: 10 })
    ])

    // 处理统计数据
    if (statsRes.status === 'fulfilled' && statsRes.value.code === 200) {
      statsData.value = statsRes.value.data
    }

    // 处理高频场景
    if (scenariosRes.status === 'fulfilled' && scenariosRes.value.code === 200) {
      frequentScenarios.value = scenariosRes.value.data || []
    }

    // 处理成功案例
    if (casesRes.status === 'fulfilled' && casesRes.value.code === 200) {
      successCases.value = casesRes.value.data?.records || casesRes.value.data || []
    }

    // 处理热门帖子
    if (hotRes.status === 'fulfilled' && hotRes.value.code === 200) {
      hotPosts.value = hotRes.value.data?.records || hotRes.value.data || []
    }

  } catch (error) {
    console.error('加载社区数据失败:', error)
  }
}

const loadPosts = async () => {
  loading.value = true
  
  try {
    const params = {
      current: pageParams.current,
      size: pageParams.size,
      sortBy: 'latest'
    }
    
    const response = await getPostList(params)
    
    if (response.code === 200) {
      const data = response.data
      const newPosts = data.records || data || []
      
      // 处理帖子数据
      const processedPosts = newPosts.map(post => ({
        ...post,
        avatar: post.avatar || defaultAvatar,
        nickname: post.isAnonymous ? '匿名用户' : (post.nickname || '用户'),
        images: post.images ? (typeof post.images === 'string' ? post.images.split(',') : post.images) : [],
        tags: post.tags || '',
        isLiked: post.isLiked || false,
        isCollected: post.isCollected || false,
        viewCount: post.viewCount || 0,
        likeCount: post.likeCount || 0,
        commentCount: post.commentCount || 0,
        collectCount: post.collectCount || 0
      }))
      
      if (pageParams.current === 1) {
        postList.value = processedPosts
      } else {
        postList.value.push(...processedPosts)
      }
      
      pageParams.current++
      
      if (processedPosts.length < pageParams.size) {
        finished.value = true
      }
    }
  } catch (error) {
    console.error('加载帖子失败:', error)
    finished.value = true
  } finally {
    loading.value = false
  }
}

const onRefresh = () => {
  refreshing.value = true
  postList.value = []
  finished.value = false
  pageParams.current = 1
  
  Promise.all([loadCommunityData(), loadPosts()]).finally(() => {
    refreshing.value = false
  })
}

const onLoad = () => {
  loadPosts()
}

const getScenarioIcon = (categoryId) => {
  const iconMap = {
    1: 'manager-o',     // 职场纠纷
    2: 'shopping-cart-o', // 消费维权
    3: 'home-o',        // 租房矛盾
    4: 'question-o'     // 其他
  }
  return iconMap[categoryId] || 'question-o'
}

const filterByScenario = (categoryId) => {
  router.push(`/community?category=${categoryId}`)
}

const showAllScenarios = () => {
  router.push('/community/scenarios')
}

const showAllSuccessCases = () => {
  router.push('/community?filter=success')
}

const showAllHotPosts = () => {
  router.push('/community?sort=hot')
}

const goToAllPosts = () => {
  router.push('/community')
}

const goToPublish = () => {
  if (!userStore.isLoggedIn) {
    showToast('请先登录')
    router.push('/login')
    return
  }
  router.push('/community/publish')
}

const goToAiDiagnosis = () => {
  router.push('/ai/diagnosis')
}

const goToTemplates = () => {
  router.push('/templates')
}

const goToMyPosts = () => {
  if (!userStore.isLoggedIn) {
    showToast('请先登录')
    router.push('/login')
    return
  }
  router.push('/profile/posts')
}

const goToPostDetail = (postId) => {
  router.push(`/community/post/${postId}`)
}

const toggleLike = async (post) => {
  if (!userStore.isLoggedIn) {
    showToast('请先登录')
    return
  }
  
  try {
    await likePost(post.id)
    post.isLiked = !post.isLiked
    post.likeCount += post.isLiked ? 1 : -1
    showToast(post.isLiked ? '点赞成功' : '取消点赞')
  } catch (error) {
    console.error('点赞操作失败:', error)
    showToast('操作失败')
  }
}

const toggleCollect = async (post) => {
  if (!userStore.isLoggedIn) {
    showToast('请先登录')
    return
  }
  
  try {
    await collectPost(post.id)
    post.isCollected = !post.isCollected
    post.collectCount += post.isCollected ? 1 : -1
    showToast(post.isCollected ? '收藏成功' : '取消收藏')
  } catch (error) {
    console.error('收藏操作失败:', error)
    showToast('操作失败')
  }
}

const previewImage = (images, startPosition) => {
  showImagePreview({
    images,
    startPosition,
    closeable: true
  })
}

const formatTime = (timeStr) => {
  const time = new Date(timeStr)
  const now = new Date()
  const diff = now - time
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  if (diff < 2592000000) return `${Math.floor(diff / 86400000)}天前`
  
  return timeStr.split(' ')[0]
}

const onTabChange = (index) => {
  activeTab.value = index
}

onMounted(() => {
  loadCommunityData()
  loadPosts()
})
</script>

<style scoped>
.community-enhanced {
  min-height: 100vh;
  background: #f7f8fa;
  padding-bottom: 50px;
}

/* 社区统计 */
.community-stats {
  background: linear-gradient(135deg, #1989fa 0%, #1976d2 100%);
  padding: 20px 16px;
  margin-top: 46px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

.stat-item {
  text-align: center;
  color: white;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  opacity: 0.8;
}

/* 通用区块样式 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: white;
  border-bottom: 1px solid #eee;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.more-btn {
  font-size: 14px;
  color: #1989fa;
  cursor: pointer;
}

/* 高频维权场景 */
.frequent-scenarios {
  background: white;
  margin-bottom: 8px;
}

.scenarios-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  padding: 16px;
}

.scenario-item {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 12px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.scenario-item:hover {
  background: #e9ecef;
}

.scenario-icon {
  width: 40px;
  height: 40px;
  background: #1989fa;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
}

.scenario-icon .van-icon {
  color: white;
  font-size: 20px;
}

.scenario-name {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 2px;
}

.scenario-count {
  font-size: 12px;
  color: #666;
}

/* 精选成功案例 */
.success-cases {
  background: white;
  margin-bottom: 8px;
}

.cases-list {
  padding: 0 16px 16px;
}

.case-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
}

.case-item:last-child {
  border-bottom: none;
}

.case-badge {
  background: #52c41a;
  color: white;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  margin-right: 12px;
  flex-shrink: 0;
}

.case-content {
  flex: 1;
  margin-right: 12px;
}

.case-title {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 4px;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.case-summary {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
  margin-bottom: 6px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.case-meta {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #999;
}

.case-amount {
  color: #ff6b35;
  font-weight: 500;
}

.case-stats {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.case-stats .stat {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #999;
}

/* 热门讨论 */
.hot-posts {
  background: white;
  margin-bottom: 8px;
}

.hot-list {
  padding: 0 16px 16px;
}

.hot-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
}

.hot-item:last-child {
  border-bottom: none;
}

.hot-rank {
  width: 24px;
  height: 24px;
  background: #f0f0f0;
  color: #666;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
  margin-right: 12px;
}

.hot-rank.top-three {
  background: linear-gradient(135deg, #ff6b35 0%, #ff8c42 100%);
  color: white;
}

.hot-content {
  flex: 1;
  margin-right: 12px;
}

.hot-title {
  font-size: 14px;
  margin-bottom: 4px;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.hot-meta {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #999;
}

/* 快速入口 */
.quick-actions {
  background: white;
  margin-bottom: 8px;
  padding: 16px;
}

.action-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.action-item:hover {
  background: #e9ecef;
}

.action-item .van-icon {
  font-size: 24px;
  color: #1989fa;
}

.action-item span {
  font-size: 12px;
  color: #333;
}

/* 最新帖子 */
.latest-posts {
  background: white;
}

.post-item {
  padding: 16px;
  border-bottom: 8px solid #f7f8fa;
  cursor: pointer;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.user-info {
  display: flex;
  align-items: center;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin-right: 12px;
}

.nickname {
  font-size: 14px;
  font-weight: 500;
  color: #323233;
  margin-bottom: 2px;
}

.post-time {
  font-size: 12px;
  color: #969799;
}

.status-tag {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
}

.status-tag.resolved {
  background: #f6ffed;
  color: #52c41a;
}

.status-tag.pending {
  background: #fff7e6;
  color: #ff976a;
}

.post-content {
  margin-bottom: 12px;
}

.post-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  line-height: 1.4;
  margin-bottom: 8px;
}

.post-summary {
  font-size: 14px;
  color: #646566;
  line-height: 1.5;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.post-images {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
  position: relative;
}

.post-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
}

.more-images {
  position: absolute;
  right: 8px;
  bottom: 8px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.post-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag {
  font-size: 12px;
  padding: 2px 8px;
  background: #f0f9ff;
  color: #1989fa;
  border-radius: 4px;
}

.post-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.post-stats {
  display: flex;
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #969799;
}

.post-actions {
  display: flex;
  gap: 16px;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #969799;
  cursor: pointer;
  transition: color 0.2s;
}

.action-item.active {
  color: #1989fa;
}
</style>